<?php
// 应用公共文件


/**
 * @param array $data
 * @return array
 * 树状结构
 */

use think\facade\Cache;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Filesystem;
/**
 * 数组 树状结构
 */
if (!function_exists('getTree')) {
 function getTree( $data)
{
    if(!is_array($data)){
        $data= json_decode($data, true);
    }

    $items = [];
    foreach ($data as $v){
        $items[$v['id']] = $v; // $items[1] =
    }
    $tree = array(); //格式化好的树
    foreach ($items as $item)
        if (isset($items[$item['pid']]))
            $items[$item['pid']]['child'][] = &$items[$item['id']];
        else
            $tree[] = &$items[$item['id']];
    return $tree;
}
}

/**
 * 生成token
 */
if(!function_exists('createToken')){
    function createToken($arr = null)
    {
        // 生成token
        $token = sha1(md5(uniqid(md5(microtime(true)), true)));
//        $arr['token'] = $token;
        // 登录过期时间 604800 一周
        Cache::set($token, $arr, 604800);
        // 保存到缓存中
        // 返回token
        return $token;
    }
}


/**
 * curl
 * @param string $url             链接
 * @param null $data              传入数据
 * @param string $type            类型
 * @param string $method          请求方法
 * @param string[] $header        header头
 * @param bool $https             是否验证证书
 * @param int $timeout            超时时间
 * @return bool|string
 */
if(!function_exists('sendCurl')){
    function sendCurl($url = 'http://www.4399.com/', $data=null, $type = 'json', $method='get', $header = array("content-type: application/json;charset='utf-8'"), $https=true, $timeout = 5)
    {
        $ch = curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
        if($https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
        }

        //默认是GET请求
        switch (strtoupper($method)){
            case 'GET':
                curl_setopt($ch, CURLOPT_POST, 0);//请求方式为get请求
                break;
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
                break;
            case 'PUT':
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
                break;
        }
        if ($data){
            switch ($type){
                case 'json':
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//请求数据
                    break;
                default:
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
            }
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);//执行请求
        curl_close($ch);//关闭curl，释放资源


        return $result;
    }
}

/**
 * 生成订单号
 */
if(!function_exists('createOrderNo')){
    function createOrderNo(){
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}

/** 上传到oss
 * @param $filePath
 * @param string $directory
 * @return false
 */
function ossUpload($filePath, $directory = 'images')
{
    $type = pathinfo($filePath, PATHINFO_EXTENSION);

    try {
        $accessKeyId = Filesystem::getDiskConfig('aliyun_oss', 'accessKeyId');
        $accessKeySecret = Filesystem::getDiskConfig('aliyun_oss', 'accessKeySecret');
        $endpoint = Filesystem::getDiskConfig('aliyun_oss', 'endpoint');
        $bucket = Filesystem::getDiskConfig('aliyun_oss', 'bucket');
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $fileName = date('YmdHis') . uniqid() . '.' . 'png';
        $pathName = $directory . '/' . date('Y-m/d') . '/' . $fileName;
        $result = $ossClient->uploadFile($bucket, $pathName, $filePath);
        @unlink($filePath);
        return $result['info']['url'];
    } catch (OssException $e) {
        return false;
    }
}